 
package com.zdkj.subway.check.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSON;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.subway.check.entity.SwAuTvmSingleAssist;
import com.zdkj.subway.check.service.SwSwAuExcelImportAndExportService;
import com.zdkj.subway.check.util.LocalDateConverter;
import com.zdkj.subway.check.util.LocalDateTimeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 收入审核导出导入实现类
 *
 * @author stw
 * @date 2020-12-10 10:55:09
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class SwSwAuExcelImportAndExportServiceImpl implements SwSwAuExcelImportAndExportService {
    //使用指定类初始化日志对象
    private static final Logger LOGGER = LoggerFactory.getLogger(SwSwAuExcelImportAndExportServiceImpl.class);
    private String parsePattern = "yyyy-MM-dd";


    /**
     * TVM单台设备SC层级的导入
     * @param excelFile
     * @return
     * @throws Exception
     */
	@Override
    public Boolean importScTvmSingleAssistBatch(final File excelFile) throws Exception {
		  List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(3).doReadSync();
		 if (CollectionUtil.isNotEmpty(listMap)) {
            List<SwAuTvmSingleAssist> listDb = new ArrayList<>();
            MultipartFileToFile.delteTempFile(excelFile);
            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 表示所在的列 和所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

                SwAuTvmSingleAssist tmpObj = new SwAuTvmSingleAssist();

                tmpObj.setId(new Integer(data.get(0)));//编号
                tmpObj.setReplyRechargeMoney(getData(data.get(11)));  //回馈的充值
                tmpObj.setReplySaleMoney(getData(data.get(12))); //售卖
                tmpObj.setReplyErrorReturnMoney(getData(data.get(13))); //退款
                tmpObj.setReplyTotal(getData(data.get(14)));//合计
				String replayReson = "系統原因".equals(data.get(15))?"1":"2";
                tmpObj.setReplyReason(replayReson);//原因
				tmpObj.setReplyContent(data.get(16));//问题描述 
				
				//追加当前机电人员ID，工号，回馈时间，回馈状态，机电协查状态,机电回馈时间等字段
               
                listDb.add(tmpObj);

            }          
             //  增加根据id批量更新回馈信息方法
            //return this.updateBatch(listDb);

        }

        return false;
       

    }

    /**
     * TVM单台设备协查导出（SC）
     * @param ids
     * @param params
     * @param response
     */
	@Override
    public void exportScSingleTvmAssist(String ids, SwAuTvmSingleAssist params,HttpServletResponse response) {
       //需要根据ID或者前台查询条件参数获取数据
	   //ids 用逗号分隔，如果ids不为空，以ids为准，否则以params为准,参考收入审核--互联网售票机--协查导出功能。
        //金额除100

        List records = new ArrayList();//查询单台设备数据,方便导出
		//需要将records对象中有关线路、站点转换成中文
		InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("TVM单台设备协查", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/SwAuTvmSingleAssistExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("TVM单台设备协查").build();
          
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);

            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出TVM单台设备协查错误");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }

            }
        }
    }
  
   

    private String getLineCode (List<Map<String,String>> lineMap,String lineName) {
        for (Map<String,String> map : lineMap){
            if(lineName.equals(map.get("NAME"))){
                return map.get("CODE");
            }
        }
        return "";
    }

    private String getStationCode (List<Map<String,String>> stationMap,String stationName,String lineCode) {
        for (Map<String,String> map : stationMap){
            if(stationName.equals(map.get("NAME")) && lineCode.equals(map.get("LINE_CODE"))){
                return map.get("CODE");
            }
        }
        return "";
    }

    /**
     * 金额转换
     * @param money
     * @return
     */
   private BigDecimal getData(String money){
	      try {
	            BigDecimal num = new BigDecimal("100");          
	            BigDecimal itemMoney = new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP);
	            itemMoney = itemMoney.multiply(num);
	            return itemMoney;

	        } catch (Exception e) {
	            return new  BigDecimal("0.00");   
	        }
	   
	   }

    private boolean parseDate(String string) {
        boolean convertSuccess = true;
        if (string == null) {
            return false;
        }

        try {
            DateUtils.parseDate(string, parsePattern);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }


}
